const DB = require('../db/db');

module.exports = {
    // 新增科室
    async add(departmentinfo) {
        let result = await DB.insert('department', departmentinfo)
        if (result.affectedRows > 0) {
            return { msg: '科室新增成功', code: 0, data: result };
        }
    },
    // 删除科室
    async del(department) {
        let result = await DB.del('department', department)
        return {
            msg: '科室删除成功', code: 0, data: result
        }
    },
    // 查询全部
    async select() {
        let sql = `SELECT 
        a.id,
        a.name,
        b.name AS branch_name,
        b.id AS branch_id
    FROM 
        department AS a
    LEFT JOIN 
        branch AS b ON a.branch_id = b.id;`;
        let result = await DB.execute(sql);
        return { msg: '查询成功', code: 0, data: result[0] };
    },
    //更新
    async update(param) {
        let result = await DB.update('department', {
            updateFields: {
                name: `"${param.name}"`,
                id: `"${param.id}"`,
                branch_id: `"${param.branch_id}"`
            },
            where_and: [`id=${param.id}`]
        });
        return { msg: '修改成功', code: 0, data: result };
    },
    // 关联院区和科室，从科室的branch_id找到院区的name
    async selectdepartmentfrombranch(param) {
        let sql = `SELECT 
        b.id,b.name,a.name As branch_name,a.id as branch_id 
        FROM  branch AS a
        LEFT JOIN department AS b
        ON a.id=b.branch_id
        where a.id=${param.id};
        `;
        let result = await DB.execute(sql);
        return { msg: '查询成功', code: 0, data: result[0] };
    }
}